import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: JSON.parse(sessionStorage.getItem('user')) || null,
    msgList: [], // 聊天消息列表
    userList: [], // 当前在线用户列表
    forbiddenWords: [],
    activeMenu: '1-1',
    openMenus: JSON.parse(localStorage.getItem('openMenus')) || ['1']
  },

  mutations: {
    // 设置用户信息
    SET_USER(state, userData) {
      if (userData.username) {
        state.user = { username: userData.username, avatar: userData.avatar }
      } else {
        console.error("缺少必要的 username 字段")
      }
      sessionStorage.setItem('user', JSON.stringify(userData))
    },

    // 清除用户信息
    CLEAR_USER(state) {
      state.user = null
      sessionStorage.removeItem('user')
    },

    // 更新用户信息（用于设置页面）
    UPDATE_USER_INFO(state, user) {
      state.user = { ...state.user, ...user }
      sessionStorage.setItem('user', JSON.stringify(state.user))
    },

    // 添加聊天消息
    ADD_CHAT_MESSAGE(state, message) {
      state.msgList.push(message)
    },

    // 更新用户列表
    UPDATE_USER_LIST(state, userList) {
      console.log("准备更新用户列表:", userList)

      if (!Array.isArray(userList)) {
        console.warn("无效的用户列表格式")
        return
      }

      if (typeof userList[0] === 'string') {
        state.userList = userList.map(username => ({
          username,
          avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
          isBanned: false
        }))
      } else {
        state.userList = userList.map(user => ({
          username: user.username,
          avatar: user.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
          isBanned: !!user.isBanned
        }))
      }

      console.log("更新后的 userList:", state.userList)
    },

    // ✅ 新增：设置整个违禁词列表
    SET_FORBIDDEN_WORDS(state, words) {
      if (Array.isArray(words)) {
        state.forbiddenWords = words.map(word => ({
          id: Date.now() + Math.random(), // 简单模拟唯一 ID
          word
        }));
      } else {
        state.forbiddenWords = [];
      }
    },

    // 设置当前激活菜单
    SET_ACTIVE_MENU(state, menuIndex) {
      state.activeMenu = menuIndex
    },

    // 设置展开菜单
    SET_OPEN_MENUS(state, menus) {
      state.openMenus = menus
      localStorage.setItem('openMenus', JSON.stringify(menus))
    },

    // 禁言用户
    BAN_USER(state, userId) {
      const user = state.userList.find(u => u.username === userId)
      if (user) {
        user.isBanned = true
      }
    },

    // 解除禁言
    UNBAN_USER(state, userId) {
      const user = state.userList.find(u => u.username === userId)
      if (user) {
        user.isBanned = false
      }
    },

    // 踢出用户
    KICK_USER(state, userId) {
      state.userList = state.userList.filter(u => u.username !== userId)
    }
  },

  actions: {
    // 登录
    login({ commit }, userData) {
      commit('SET_USER', userData)
    },

    // 登出
    logout({ commit }) {
      commit('CLEAR_USER')
    },

    // 添加聊天消息
    addChatMessage({ commit }, message) {
      commit('ADD_CHAT_MESSAGE', message)
    },

    // 更新用户列表
    updateUserList({ commit }, userList) {
      commit('UPDATE_USER_LIST', userList)
    },

    // 更新用户信息（设置页面使用）
    updateUserInfo({ commit }, user) {
      commit('UPDATE_USER_INFO', user)
    },

    // ✅ 新增：更新整个违禁词列表（来自后端或 WebSocket）
    updateForbiddenWords({ commit }, words) {
      if (!Array.isArray(words)) {
        console.warn("非法违禁词格式，期望为数组")
        return
      }

      const formatted = words.map((word, index) => ({
        id: index + 1,
        word
      }))

      commit('SET_FORBIDDEN_WORDS', formatted)
    },

    // 设置当前激活菜单
    updateActiveMenu({ commit }, menuIndex) {
      commit('SET_ACTIVE_MENU', menuIndex)
    },

    // 设置展开菜单
    updateOpenMenus({ commit }, menus) {
      commit('SET_OPEN_MENUS', menus)
    },

    // 禁言用户
    banUser({ commit }, userId) {
      commit('BAN_USER', userId)
    },

    // 解除禁言
    unbanUser({ commit }, userId) {
      commit('UNBAN_USER', userId)
    },

    // 踢出用户
    kickUser({ commit }, userId) {
      commit('KICK_USER', userId)
    }
  },

  getters: {
    getMsgList: state => state.msgList,
    getUserList: state => state.userList,
    getForbiddenWords: state => state.forbiddenWords,
    getActiveMenu: state => state.activeMenu,
    getOpenMenus: state => state.openMenus
  },

  modules: {}
})